<template>
  <div class="details">
    <div class="deta-top">
      <span @click="back"></span>
    </div>
    <div class="deta-box">
      <img class="autoImg" :src="detailData.large_img" />
    </div>
    <div class="deta-rule">
      <div class="rule-box">
        <div class="rule-name">
          <div class="name">
            <div class="ch-name">{{ detailData.name }}</div>
            <div class="en-name">{{ detailData.enname }}</div>
          </div>
          <div class="price">
            <span>&yen;{{ detailData.price }}</span>
          </div>
        </div>
        <van-divider
          :style="{
            color: '#f7f7f7',
            borderColor: '#ccc',
            padding: '0 16px',
            marginTop: '5px',
          }"
        />
        <div class="rule-rules">
          <div class="rules" v-for="(val, k) in detailData.rulesData" :key="k">
            <div class="rules-title">{{ val.title }}</div>
            <div class="rules-item">
              <div
                :class="{ active: val.currentIndex === i }"
                v-for="(v, i) in val.rule"
                :key="i"
                @click="changeRule(val, i)"
              >
                {{ v.title }}
              </div>
            </div>
          </div>
        </div>
        <van-divider
          :style="{
            color: '#f7f7f7',
            borderColor: '#ccc',
            padding: '0 16px',
            marginTop: '5px',
          }"
        />
        <div class="rule-count">
          <div class="count-select">
            <span>选择数量</span>
          </div>
          <div class="count-change">
            <van-stepper
              v-model="count"
              theme="round"
              button-size="22"
              disable-input
            />
          </div>
        </div>
        <van-divider
          :style="{
            color: '#f7f7f7',
            borderColor: '#ccc',
            padding: '0 16px',
            marginTop: '5px',
          }"
        />
        <div class="rule-desc">
          <div class="desc-title">
            <span>商品描述</span>
          </div>
          <div class="desc-content">
            <div
              class="content"
              v-for="(val, key) in detailData.desc"
              :key="key"
            >
              <span>{{ val }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="deta-action">
      <van-goods-action>
        <van-goods-action-icon
          icon="bag"
          text="购物袋"
          color="#999"
          :badge="shopbagCount > 0 ? shopbagCount : ''"
          @click="toShopbag"
        />
        <van-goods-action-icon
          icon="star"
          text="收藏"
          :color="isCollection ? '#21b276' : '#999'"
          @click="addCollection"
        />
        <van-goods-action-button
          type="primary"
          text="加入购物袋"
          color="#999"
          @click="addPocket"
        />
        <van-goods-action-button
          type="danger"
          text="立即购买"
          color="#21b276"
          @click="buyNow"
        />
      </van-goods-action>
    </div>
  </div>
</template>
<script>
import "../assets/less/details.less";
import {mapState , mapMutations} from 'vuex'
export default {
  name: "Details",
  data() {
    return {
      pid: "",
      detailData: {},
      isCollection: false,
      // shopbagCount: 0,
      count: 1,
    };
  },
  created() {
    this.pid = this.$route.params.pid;
    this.getDetailData();
    this.getCollection();
  },
  computed:{
    ...mapState(['shopbagCount'])
  },
  methods: {
    ...mapMutations(['shopbagChange']),
    back() {
      this.$router.back();
    },
    getDetailData() {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        //请求方式
        method: "GET",
        url: this.baseUrl + "/productDetail",
        params: {
          appkey: this.appkey,
          pid: this.pid,
        },
      })
        .then((res) => {
          this.$toast.clear();

          if (res.data.code === 600) {
            let data = res.data.result[0];

            let rules = ["cream", "tem", "sugar", "milk"];

            data.rulesData = [];
            rules.forEach((v) => {
              if (!data[v]) {
                return;
              }

              let rulesText = data[v].split("/");

              let currentRule = {
                title: data[v + "_desc"],
                currentIndex: 0,
                rule: [],
              };

              rulesText.forEach((item) => {
                let o = {
                  title: item,
                };
                currentRule.rule.push(o);
              });

              data.rulesData.push(currentRule);
            });

            data.desc = data.desc.split(/\n/);


            this.detailData = data;
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    changeRule(item, index) {
      if (item.currentIndex === index) {
        return;
      }

      item.currentIndex = index;
    },
    like() {
      let tokenString = this.$cookies.get("tokenString");
      // let tokenString = localStorage.getItem("tokenString");

      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      this.axios({
        
        method: "POST",
        url: this.baseUrl + "/like",
        data: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
        },
      })
        .then((res) => {
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code === 800) {
            
            this.isCollection = true;
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    nolike(){
      let tokenString = this.$cookies.get("tokenString");
      // let tokenString = localStorage.getItem("tokenString");

      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      this.axios({
        
        method: "POST",
        url: this.baseUrl + "/notlike",
        data: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
        },
      })
        .then((res) => {
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code === 900) {
            
            if(res.data.result === 1){
              this.isCollection = false;
            }
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    addCollection() {
      if(this.isCollection){
        this.nolike();
      }else{
        this.like();
      }
    },
    getCollection(){
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        return 
      }
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      this.axios({
        
        method: "GET",
        url: this.baseUrl + "/findlike",
        params: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
        },
      })
        .then((res) => {
          this.$toast.clear();

          if (res.data.code == 700) {
            return 
          }

          if (res.data.code === 1000) {
            
            
            if(res.data.result.length > 0){
              this.isCollection = true;
            }
          } 
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    addPocket(){
      let tokenString = this.$cookies.get("tokenString");
      // let tokenString = localStorage.getItem("tokenString");

      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }
      let rules = [];
      this.detailData.rulesData.forEach((item) =>{
        rules.push(item.rule[item.currentIndex].title);
      })
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      this.axios({
        
        method: "POST",
        url: this.baseUrl + "/addShopcart",
        data: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
          count:this.count,
          rule:rules.join("/")
        }
      })
        .then((res) => {
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code === 3000) {
            
            if(res.data.status === 1){
              this.shopbagChange(this.shopbagCount + 1);
              this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            }
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    toShopbag(){
      this.$router.push({name:"Shopbag"})
    },
    buyNow(){
      this.addPocket();
      this.$router.push({name:"Shopbag"})

    }
  },
};
</script>